﻿using System.Windows;
using System.Windows.Controls;
using SuperGo.Silverlight.WebApp;
using System.ComponentModel;

namespace SuperGo.Silverlight {
	public partial class Preferences {
		public class DisplayUser : INotifyPropertyChanged {
			public string PlayerName { get; set; }
			public string Username { get; set; }
			public string Password { get; set; }
			public string Email { get; set; }
			public WsPlayer CurrentWsPlayer { get; set; }

			public const string BLANKPASSWORD = "********";

			public void SetUser(WsPlayer wsPlayer) {
				PlayerName = wsPlayer.Name;
				Username = wsPlayer.IgsUsername;
				if (!string.IsNullOrEmpty(wsPlayer.IgsPassword))
					Password = BLANKPASSWORD;
				else
					Password = "";
				Email = wsPlayer.Email;
				CurrentWsPlayer = wsPlayer;

				PropertyChanged(this, new PropertyChangedEventArgs("PlayerName"));
				PropertyChanged(this, new PropertyChangedEventArgs("Username"));
				PropertyChanged(this, new PropertyChangedEventArgs("Password"));
				PropertyChanged(this, new PropertyChangedEventArgs("Email"));
			}

			public WsPlayer GetUser() {
				WsPlayer player = new WsPlayer {
					PlayerId = CurrentWsPlayer.PlayerId,
					Email = Email,
					IgsUsername = Username
				};

				if (Password != BLANKPASSWORD)
					player.IgsPassword = Password;

				return player;
			}

			public event PropertyChangedEventHandler PropertyChanged;
		}

		protected DisplayUser CurrentDisplayUser { get; private set; }

		public Preferences() {
			InitializeComponent();
			Loaded += new RoutedEventHandler(Preferences_Loaded);
		}

		void Preferences_Loaded(object sender, RoutedEventArgs e) {
			_buttonPanel = (ButtonPanel)_goPanel.FindName("_buttonPanel");

			_submit = (Button)_buttonPanel.FindName("_submit");
			_submit.Click += new RoutedEventHandler(submit_Click);

			_cancel = (Button)_buttonPanel.FindName("_cancel");
			_cancel.Click += new RoutedEventHandler(cancel_Click);

			_errorMessage = (TextBlock)_goPanel.FindName("_errorMessage");

			CurrentDisplayUser = new DisplayUser();
			_goPanel.DataContext = CurrentDisplayUser;
		}

		void cancel_Click(object sender, RoutedEventArgs e) {
			Page.ShowGamePage();
		}

		public void SetUser(WsPlayer wsPlayer) {
			CurrentDisplayUser.SetUser(wsPlayer);
			_errorMessage.Visibility = System.Windows.Visibility.Collapsed;
		}

		void submit_Click(object sender, RoutedEventArgs e) {
			Page.UpdatePreferences(CurrentDisplayUser.GetUser());
		}

		///<summary>
		///occurs after submit_Click calls UpdatePreferences on the server if there
		///       was an error.
		///</summary>
		public void ShowError(string errorMessage) {
			_errorMessage.Text = errorMessage;
			_errorMessage.Visibility = System.Windows.Visibility.Visible;
		}
	}
}
